﻿using System.Diagnostics;
using Game.Common;
using Game.Map.Extensions;
using Game.Objects;
using Game.Map;

namespace Game.Actions
{
    public class MoveUnit : UnitAction
    {
        readonly Vehicle _Vehicle;
        readonly GamePath _Path;
        readonly IGameMap _GameMap;
        
        public MoveUnit(IGameMap gameMap, 
                        Vehicle vehicle, 
                        GamePath pathToMove)
        {
            _GameMap = gameMap;
            _Vehicle = vehicle;
            _Path = pathToMove;
            Check();
        }

        void Check()
        {
            double moveAmount = _Path.CalcTerrainCost(_GameMap);
            Debug.Assert(_Vehicle.Movement.Value >= moveAmount);
        }

        public override bool CanExecute()
        {
            var end = _GameMap.Fields[_Path.LastPoint];
            
            if (end.VehicleX().Vehicle != null)
            {
                return false;
            }
            
            if (_Vehicle.Movement.Value == 0)
            {
                return false;
            }
            
            return true;
        }
        
        protected override ActionResult Execute(
            GameTurn turn,
            Context context)
        {
            var end = _GameMap.Fields[_Path.LastPoint];
            
            if (end.VehicleX().Vehicle != null)
            {
                return null;
            }
            
            _GameMap.MoveX().MoveTo(context.ActionExecutor,_Path, _Vehicle, turn);
            return null;
        }
    }
}
